/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 对象工具类
 *
 * @author fzh
 */
public class XrObjectUtil {

	/**
	 * 判断对象中的字段值是否全部为空
	 * @param object 对象
	 * @return boolean
	 */
	public static boolean checkOfAllNull(Object object) {
		if (ObjectUtils.isEmpty(object)) {
			return true;
		}
		List<Object> list = new ArrayList<>();
		Class<?> clazz = object.getClass();
		List<Field> fields = new ArrayList<>();
		while (ObjectUtils.isNotEmpty(clazz)) {
			fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
			clazz = clazz.getSuperclass();
		}
		try {
			for (Field field : fields) {
				int mod = field.getModifiers();
				if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
					continue;
				}
				field.setAccessible(true);
				Object fieldValue = field.get(object);
				if (ObjectUtils.isNotEmpty(fieldValue) && StringUtils.isNotBlank(fieldValue.toString())) {
					list.add(fieldValue);
				}
			}
			if (list.size() > 0) {
				return false;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 判断对象是否为空
	 * @param object 对象
	 * @return boolean
	 */
	private static boolean isEmpty(Object object) {
		if (object == null) {
			return true;
		}
		if (object instanceof String && (object.toString().equals(""))) {
			return true;
		}
		if (object instanceof Collection && ((Collection<?>) object).isEmpty()) {
			return true;
		}
		if (object instanceof Map && ((Map<?, ?>) object).isEmpty()) {
			return true;
		}
		return object instanceof Object[] && ((Object[]) object).length == 0;
	}

	/**
	 * 判断对象是否为非空
	 * @param object 对象
	 * @return boolean
	 */
	private static boolean isNotEmpty(Object object) {
		return !isEmpty(object);
	}

}
